import type { CarouselRef } from 'ant-design-vue/es/carousel'
import { debounce } from 'lodash-es'
import { onMounted, onUnmounted, type Ref } from 'vue'

export default function useCarousel(
  container: Ref<HTMLElement | undefined>,
  carouselRef: Ref<CarouselRef | undefined>,
  changeCarouselPage?: () => void
) {
  const timeoutValue = 5000

  let carTimeout: NodeJS.Timeout

  const mouseover = debounce(() => {
    // console.log('mouseover')
    handleChangeCarouselPage()
  }, 250)

  const mousemove = debounce(() => {
    // console.log('mousemove')
    handleChangeCarouselPage()
  }, 250)

  function click() {
    // console.log('click')
    handleChangeCarouselPage()
  }

  const touchstart = () => {
    // console.log('touchstart')
    handleChangeCarouselPage()
  }

  function handleChangeCarouselPage() {
    if (carTimeout) clearTimeout(carTimeout)
    carTimeout = setTimeout(() => {
      if (carouselRef.value) {
        carouselRef.value.next()
        if (changeCarouselPage) changeCarouselPage()
      }
    }, timeoutValue)
  }

  onMounted(() => {
    // console.log('onMounted useCarousel')
    if (container.value) {
      container.value.addEventListener('mouseover', mouseover)
      container.value.addEventListener('mousemove', mousemove)
      container.value.addEventListener('click', click)
      container.value.addEventListener('touchstart', touchstart)
    }
  })

  onUnmounted(() => {
    // console.log('onUnmounted useCarousel')
    if (container.value) {
      container.value.removeEventListener('mouseover', mouseover)
      container.value.removeEventListener('mousemove', mousemove)
      container.value.removeEventListener('click', click)
      container.value.removeEventListener('touchstart', touchstart)
    }
  })
}
